package controller;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.ResourceBundle;

import application.AlertDialog;
import bean.User;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TableView.TableViewSelectionModel;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.Image;
import javafx.stage.DirectoryChooser;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.Window;
import javafx.stage.WindowEvent;
import util.ExcelUtil;
import util.khxxUtil;

public class CustomerController implements Initializable {

    @FXML
    private Button updateBtn;

    @FXML
    private TextField cusName;

    @FXML
    private Button searchBtn;

    @FXML
    private TableColumn<User, String> bankCol;

    @FXML
    private TableColumn<User, String> addTelCol;

    @FXML
    private Button addBtn;

    @FXML
    private TableColumn<User, String> shCol;

    @FXML
    private TableColumn<User, String> areaCol;

    @FXML
    private TableColumn<User, String> bzCol;

    @FXML
    private Button delBtn;

    @FXML
    private TableColumn<User, String> linkManCol;

    @FXML
    private TableColumn<User, String> noCol;

    @FXML
    private TableView<User> tv_cus;

    @FXML
    private TableColumn<User, String> cusNameCol;
    
    List<User> cusList = new ArrayList<User>();

    @FXML
    void delCustomAction(ActionEvent event) {
    	TableViewSelectionModel<User> selected = tv_cus.getSelectionModel();
    	User user = selected.getSelectedItem();
    	if(AlertDialog.confirmDialog("删除？", "确定删除第"+(user.getNo())+"行客户信息？")){
    		khxxUtil.delMsg(Integer.parseInt(user.getNo())-1);
    		configCustomer();
    	}
    }
    
    /**
     * 导出客户信息
     * @param event
     */
    @FXML
    void exportKhxxAction(ActionEvent event){
	    // 1.获取文件所属窗体
	    Window window  = ((Button)event.getSource()).getScene().getWindow();
	    // 2.文件选择框
	    DirectoryChooser fileChooser = new DirectoryChooser();
	    // 2.1获取上次记录文件夹路径
	    fileChooser.setTitle("设置导出Excel文件路径");
	    File file = fileChooser.showDialog(window);
	    if(file != null){
	    	ObservableList<User> list = tv_cus.getItems();
			Boolean flag = ExcelUtil.outputExcel(list, file);
			if(flag){
				AlertDialog.informationAlert("文件导出成功", "", window);
			}
	    }
    }
    
    @FXML
    void updateCusAction(ActionEvent event) {
    	TableViewSelectionModel<User> selected = tv_cus.getSelectionModel();
    	User user = selected.getSelectedItem();
    	Stage stage = new Stage();
        Parent root;
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getClassLoader().getResource("view/UpdateView.fxml"));
		try {
			root = fxmlLoader.load();
			UpdateController controller = fxmlLoader.getController();
			user.setType(true);
			controller.initData(user,Integer.parseInt(user.getNo())-1);
			stage.setScene(new Scene(root));
	        stage.setTitle("客户信息维护");
	        stage.initModality(Modality.WINDOW_MODAL);
	        stage.setResizable(false);
	        stage.getIcons().add(new Image("/image/change.png"));
	        stage.initOwner(
	        		((Node) event.getSource()).getScene().getWindow());
	        stage.show();
	        stage.setOnHidden(new EventHandler<WindowEvent>() {

				@Override
				public void handle(WindowEvent event) {
					configCustomer();
				}
			});
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }

    @FXML
    void addCusAction(ActionEvent event) {
    	Stage stage = new Stage();
        Parent root;
		try {
			root = FXMLLoader.load(getClass().getClassLoader().getResource("view/UpdateView.fxml"));
			stage.setScene(new Scene(root));
	        stage.setTitle("客户信息维护");
	        stage.initModality(Modality.WINDOW_MODAL);
	        stage.setResizable(false);
	        stage.getIcons().add(new Image("/image/change.png"));
	        stage.initOwner(((Node) event.getSource()).getScene().getWindow());
	        stage.show();
	        stage.setOnHidden(new EventHandler<WindowEvent>() {

				@Override
				public void handle(WindowEvent event) {
					configCustomer();
				}
			});
	      
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }

    @FXML
    void searchCusAction(ActionEvent event) {
    	List<User> userList = new ArrayList<User>();
    	if(cusName.getText().equals("")){
    		userList = cusList;
    	}
    	List<HashMap<String, String>> msg = khxxUtil.Search("GFMC", cusName.getText());
    	if(msg.size() == 0){
    		AlertDialog.informationAlert("提示", "没有找到此记录", ((Node) event.getSource()).getScene().getWindow());
    		return;
    	}
		for (int i = 0; i < msg.size(); i++) {
			User user = new User();
			user.setNo(msg.get(i).get("NO"));
			user.setName(msg.get(i).get("GFMC"));
			user.setArea(msg.get(i).get("AREA"));
			user.setLinkman(msg.get(i).get("LXR"));
			user.setSh(msg.get(i).get("NSRSBH"));
			user.setBz(msg.get(i).get("BZ"));
			user.setDzdh(msg.get(i).get("DZDH"));
			user.setYhzh(msg.get(i).get("BANK"));
			userList.add(user);
		}
		configCustomerTable(userList);
    }

	@Override
	public void initialize(URL location, ResourceBundle resources) {
		configCustomer();
	}
	
	private void configCustomer(){
		cusList = new ArrayList<User>();
		List<HashMap<String, String>> msg = khxxUtil.getMsg();
		for (int i = 0; i < msg.size(); i++) {
			User user = new User();
			user.setNo(msg.get(i).get("NO"));
			user.setName(msg.get(i).get("GFMC"));
			user.setArea(msg.get(i).get("AREA"));
			user.setLinkman(msg.get(i).get("LXR"));
			user.setSh(msg.get(i).get("NSRSBH"));
			user.setBz(msg.get(i).get("BZ"));
			user.setDzdh(msg.get(i).get("DZDH"));
			user.setYhzh(msg.get(i).get("BANK"));
			cusList.add(user);
		}
		configCustomerTable(cusList);
	}
	
	
	/**
     * 初始化商品列
     * @param cusList
     * @return
     */
	public void configCustomerTable(List<User> cusList) {
		noCol.setCellValueFactory(new PropertyValueFactory<User,String>("no"));
		areaCol.setCellValueFactory(new PropertyValueFactory<User,String>("area"));
		cusNameCol.setCellValueFactory(new PropertyValueFactory<User,String>("name"));
		linkManCol.setCellValueFactory(new PropertyValueFactory<User,String>("linkman"));
		shCol.setCellValueFactory(new PropertyValueFactory<User,String>("sh"));
		addTelCol.setCellValueFactory(new PropertyValueFactory<User,String>("dzdh"));
		bankCol.setCellValueFactory(new PropertyValueFactory<User,String>("yhzh"));
		bzCol.setCellValueFactory(new PropertyValueFactory<User,String>("bz"));
		//javaFx放置数据集合
		ObservableList<User> list = FXCollections.observableArrayList();
		for (User customer : cusList) {
			list.add(customer);
		}
		
		tv_cus.setItems(list);
	}

}

